package com.studentportalen;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ExamSimpleCursorAdapter extends SimpleCursorAdapter {
	
	private final Context context;
	private final int layout;
	private final Cursor c;
	private final int studentId;
	
	public ExamSimpleCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to) {
		super(context, layout, c, from, to);
		
		this.context = context;
		this.layout = layout;
		this.c = c;
		studentId = -1;
	}
	
	public ExamSimpleCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, int studentId) {
		super(context, layout, c, from, to);
		
		this.context = context;
		this.layout = layout;
		this.c = c;
		this.studentId = studentId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		DBHelper db = Global.getDBHelper();
		
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		View rowView = inflater.inflate(layout, parent, false);
		CheckBox cb = (CheckBox) rowView.findViewById(R.id.list_exam_checkbox);
		TextView course = (TextView) rowView.findViewById(R.id.list_exam_course);
		TextView info = (TextView) rowView.findViewById(R.id.list_exam_info);
		
		//move to correct row
		c.moveToPosition(position);
		
		//get course name
		course.setText(c.getString(c.getColumnIndex("name")));
		
		//get course info
		info.setText(c.getString(c.getColumnIndex("info")));
		
		// Check cb if student registered for exam
		int courseId = c.getInt(c.getColumnIndex("_id"));
		
		// get students personal code for exam, will be -1 if not registered
		int code = db.studentRegisteredForExam(studentId, courseId);
		
		if (code >= 0) {
			cb.setChecked(true);
			info.append(", code: " + code);
		}

		return rowView;
	}
}
